package com.astn.bks.util;

import java.util.HashMap;
import java.util.Map;

import org.xmlrpc.android.BkSXMLRPCClient;
import org.xmlrpc.android.HttpPostParameter;

import com.astn.entity.booking.QuoteUser;

public class WebserviceUtils {
	private static String serviceUrl;
	private static BkSXMLRPCClient client;
	private static String username;
	private static String password;
	private static QuoteUser user;

	public static void setLoginInfo(String loginName, String password) {
		username = loginName;
		WebserviceUtils.password = password;
	}

	public static void initial(String urlService) {
		serviceUrl = urlService;
	}

	@SuppressWarnings("unchecked")
	public static boolean login(String componentName, String method) {
		boolean ok = true;
		Map<String, Object> mapPara = new HashMap<String, Object>();
		mapPara.put("USERNAME", username);
		mapPara.put("PASSWORD", password);
		client = new BkSXMLRPCClient(serviceUrl, componentName);
		try {
			Object obj = client.callEx(method, mapPara);
			ok = (Boolean) obj;
			if (ok) {
				try {
					Object userObj = client.callEx("getUserInfo", mapPara);
					Map<String, Object> mapUser = (Map<String, Object>) userObj;
					user = new QuoteUser();
					int id = Integer.parseInt(mapUser.get("id").toString());
					user.setId(id);
					user.setName((String) mapUser.get("name"));
					int type = 1;
					try {
						type = Integer.parseInt(mapUser.get("type").toString());
					} catch (Exception e) {
					}
					user.setType(type);
					user.setPhone(mapUser.get("phone").toString());
					user.setAddress(mapUser.get("address").toString());
				} catch (Exception e) {
					return ok;
				}
			}
		} catch (Exception e) {
			return false;
		}
		return ok;
	}

	public static Object call(String componentName, String method,
			Map<String, Object> mapPara) {
		client = new BkSXMLRPCClient(serviceUrl, componentName);
		Map<String, Object> mapNewPara = new HashMap<String, Object>();
		mapNewPara.put("USERNAME", username);
		mapNewPara.put("PASSWORD", password);
		if (mapPara != null) {
			for (String k : mapPara.keySet()) {
				mapNewPara.put(k, mapPara.get(k));
			}
		}
		try {
			return client.callEx(method, mapNewPara);
		} catch (Exception e) {
			return null;
		}
	}

	public static void setUser(QuoteUser us) {
		user = us;
	}

	public static QuoteUser getUser() {
		return user;
	}
}
